package cn.com.zpark.utils;

import java.sql.*;

/**
 * @PackageName: cn.com.zpark.utils
 * @ClassName: JDBCUtils
 * @Description:JDBC工具类，注册驱动获取连接，关闭连接对象
 * @author: RZS
 * @date: 2021/10/27  10:24
 */
public class JDBCUtils {
    private static String url;
    private static String driver;
    private static String username;
    private static String password;

    // 初始化变量
    static {
        url = "jdbc:mysql://192.168.80.142:3306/mydb1?useSSL=false&serverTimezone=UTC&characterEncoding=UTF-8";
        driver = "com.mysql.jdbc.Driver";
        username = "root";
        password = "root";
    }

    /**
     * 获取数据库连接对象
     * @return
     * @throws Exception
     */
    public static Connection getConn() throws Exception {
        // 注册驱动
        Class.forName(driver);
        // 获取连接
        Connection conn = DriverManager.getConnection(url, username, password);
        return conn;
    }

    /**
     * 关闭连接对象
     * @param res
     * @param stat
     * @param conn
     */
    public static void close(ResultSet res, Statement stat, Connection conn){
        if (res != null) {
            try {
                res.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (stat != null) {
            try {
                stat.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}












